package thesis.filesharing.dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import thesis.filesharing.common.exception.system.AppSystemException;
import thesis.filesharing.dao.StudentDAO;
import thesis.filesharing.dao.util.EMF;
import thesis.filesharing.model.Role;
import thesis.filesharing.model.Student;
import thesis.filesharing.web.auth.Roles;

@Repository
public class StudentDAOImpl implements StudentDAO {

	@SuppressWarnings("unchecked")
	@Override
	public Student findStudentById(String studentId) {
		EntityManager em = null;
		try {
			em = EMF.get().createEntityManager();
			String jpaql = "SELECT s FROM Student s WHERE s.studentId = :studentId";
			Query query = em.createQuery(jpaql);
			query.setParameter("studentId", studentId);
			List<Student> students = (List<Student>) query.getResultList();
			if (students != null && !students.isEmpty()) {
				return students.get(0);
			}
			return null;
		} catch (Exception ex) {
			ex.printStackTrace();
			throw new AppSystemException(ex);
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public Student findStudentByEmail(String studentEmail) {
		EntityManager em = null;
		try {
			em = EMF.get().createEntityManager();
			String jpaql = "SELECT s FROM Student s WHERE s.studentEmail = :studentEmail";
			Query query = em.createQuery(jpaql);
			query.setParameter("studentEmail", studentEmail);
			List<Student> students = (List<Student>) query.getResultList();
			if (students != null && !students.isEmpty()) {
				return students.get(0);
			}
			return null;
		} catch (Exception ex) {
			ex.printStackTrace();
			throw new AppSystemException(ex);
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public Student saveStudent(Student student) {
		EntityManager em = null;
		EntityTransaction transaction = null;
		
		try {
			em = EMF.get().createEntityManager();
			transaction = em.getTransaction();
			transaction.begin();
			
			// Get student role
			String jpaql = "SELECT r FROM Role r WHERE r.roleName = :roleName";
			Query query = em.createQuery(jpaql);
			query.setParameter("roleName", Roles.ROLE_STUDENT.getRole());
			List<Role> roles = (List<Role>) query.getResultList();
			if (roles != null && !roles.isEmpty()) {
				student.setRole(roles.get(0));
			}
			
			// Persist student
			em.persist(student);
			em.flush();
			
			transaction.commit();
			return student;
		} catch (Exception ex) {
			if (transaction != null && transaction.isActive()) {
				transaction.rollback();
			}
			ex.printStackTrace();
			throw new AppSystemException(ex);
		}
	}
}
